package xyz.scootaloo.draft.nio.basic;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Objects;

/**
 * @author flutterdash@qq.com
 * @since 2021/5/20 9:41
 */
public class ChannelDemo {

    public static void main(String[] args) throws IOException {
        File file = new File(
                Objects.requireNonNull(
                        ChannelDemo.class.getClassLoader()
                                .getResource("data/word.txt")).getFile());
        RandomAccessFile aFile = new RandomAccessFile(file, "rw");
        FileChannel inChannel = aFile.getChannel();

        ByteBuffer buf = ByteBuffer.allocate(18);

        int bytesRead = inChannel.read(buf);
        while (bytesRead != -1) {

            System.out.println("Read " + bytesRead);
            buf.flip();

            while(buf.hasRemaining()){
                System.out.print((char) buf.get());
            }

            buf.clear();
            bytesRead = inChannel.read(buf);
        }
        aFile.close();
    }

}
